import { IMTableType } from "@/types/table";
import {
  fetchPopularDataById,
  fetchScoreDataById,
  fetchVipDataById,
} from "./utils";
import { tmp_proxy, fetchList, showDrawer } from ".";
import { AxiosResponse } from "axios";
import { tableLoading } from "./table";
import { drawerTitle } from "./drawer";
import { DrawerFormStateType } from "./type";
export const operateType = ref<any>("");
export const tableActiveKey = ref(0);
export const tabPower = reactive([true, true, true]);
export const defaultColumns = reactive([
  [
    {
      title: getProxyT("base.index"),
      dataIndex: "index",
      key: "index",
    },
    {
      title: getProxyT("table5"),
      dataIndex: "level",
      key: "level",
    },
    {
      title: getProxyT("table24"),
      dataIndex: "name",
      key: "name",
    },
    { title: getProxyT("table25"), dataIndex: "src", key: "src" },
    {
      title: getProxyT("table26"),
      dataIndex: "icon",
      key: "icon",
    },
    { title: getProxyT("table27"), dataIndex: "url", key: "url" },
    {
      title: computed(() => `${$t("table28")}(USDT)`),
      dataIndex: "price",
      key: "price",
    },
    {
      title: getProxyT("table29"),
      dataIndex: "accessData",
      key: "accessData",
    },
    {
      title: getProxyT("table30"),
      dataIndex: "count",
      key: "count",
    },
    {
      title: getProxyT("table31"),
      dataIndex: "status",
      key: "status",
    },
    { title: getProxyT("base.action"), key: "action" },
  ],
  [
    {
      title: getProxyT("base.index"),
      dataIndex: "index",
      key: "index",
    },
    {
      title: getProxyT("table6"),
      dataIndex: "level",
      key: "level",
    },
    {
      title: getProxyT("table24"),
      dataIndex: "name",
      key: "name",
    },
    {
      title: getProxyT("table32"),
      dataIndex: "title",
      key: "title",
    },
    { title: getProxyT("table25"), dataIndex: "url", key: "url" },
    {
      title: getProxyT("table26"),
      dataIndex: "icon",
      key: "icon",
    },
    {
      title: getProxyT("table33"),
      dataIndex: "rule",
      key: "rule",
    },
    {
      title: getProxyT("table29"),
      dataIndex: "accessData",
      key: "accessData",
    },
    {
      title: getProxyT("table30"),
      dataIndex: "count",
      key: "count",
    },
    {
      title: getProxyT("table31"),
      dataIndex: "status",
      key: "status",
    },
    { title: getProxyT("base.action"), key: "action" },
  ],
  [
    {
      title: getProxyT("base.index"),
      dataIndex: "index",
      key: "index",
    },
    {
      title: getProxyT("table7"),
      dataIndex: "level",
      key: "level",
    },
    {
      title: getProxyT("table24"),
      dataIndex: "name",
      key: "name",
    },
    {
      title: getProxyT("table26"),
      dataIndex: "icon",
      key: "icon",
    },
    {
      title: getProxyT("table34"),
      dataIndex: "rule",
      key: "rule",
    },
    {
      title: getProxyT("table35"),
      dataIndex: "award",
      key: "award",
    },
    {
      title: getProxyT("table29"),
      dataIndex: "accessData",
      key: "accessData",
    },
    {
      title: getProxyT("table36"),
      dataIndex: "count",
      key: "count",
    },
    {
      title: getProxyT("table31"),
      dataIndex: "status",
      key: "status",
    },
    { title: getProxyT("base.action"), key: "action" },
  ],
]);

export let columns = reactive<IMTableType[]>([
  ...defaultColumns[tableActiveKey.value],
]);
export const drawerFormState = reactive<any>({});
export const resetFormState = (formState) => {
  const defaultFormState = reactive<DrawerFormStateType>([
    {
      src: undefined,
      icon: undefined,
      url: undefined,
      level: undefined,
      id: undefined,
      name: undefined,
      indate: undefined,
      price: undefined,
      status: 0,
      addFriendNum: undefined,
      addContactNum: undefined,
      redPacketNum: undefined,
      giftNum: undefined,
      userFilterFlag: false,
      privateService: false,
      whoSeenMeFlag: false,
      offlinePartyFlag: false,
      allPhotoFlag: false,
      privateMedal: false,
      worldChannelVoice: false,
      chatBubble: false,
      color: undefined,
      addFriendIsMember: true,
    },
    {
      level: undefined,
      id: undefined,
      url: undefined,
      icon: undefined,
      name: undefined,
      title: undefined,
      status: 0,
      rule: undefined,
      color: undefined,
    },
    {
      level: undefined,
      id: undefined,
      icon: undefined,
      name: undefined,
      status: 0,
      rule: undefined,
      award: 1,
      privateClub: false,
      privateService: false,
      onlineHideFlag: false,
      clubHideMemberFlag: false,
      hideLocationFlag: false,
      bubbleChatFlag: false,
    },
  ]);
  const currentFormState = defaultFormState[tableActiveKey.value];
  if (tableActiveKey.value === 0) {
    Object.keys(formState).forEach((key) => {
      if (key != "addFriendIsMember") {
        formState[key] = currentFormState[key];
      }
    });
    return;
  }
  initObjAttr(formState, currentFormState);
};
resetFormState(drawerFormState);
const defineGetDataApiMap = (data) => {
  const handleAdd = async (number) => {
    if (number === 0) {
      tableLoading.value = true;
      await fetchVipDataById();
      tableLoading.value = false;
      drawerTitle.value = $t("base.addMemberLevel");
    }
    if (number === 1) {
      await fetchPopularDataById();
      drawerTitle.value = $t("base.addPopularLevel");
    }
    if (number === 2) drawerTitle.value = $t("base.addScoreLevel");
    showDrawer();
  };
  const handleUpdate = async (number) => {
    if (number === 0) {
      tableLoading.value = true;
      await fetchVipDataById(data);
      tableLoading.value = false;
      drawerTitle.value = $t("base.editMemberLevel");
    }
    if (number === 1) {
      await fetchPopularDataById(data);
      drawerTitle.value = $t("base.editPopularLevel");
    }
    if (number === 2) {
      await fetchScoreDataById(data);
      drawerTitle.value = $t("base.editScoreLevel");
    }
    showDrawer();
  };
  const handleUpdateStatus = (number) => {
    const defineApiMap = ({ id }) => {
      return new Map([
        [0, () => gradeApi.updateVipStatus({ editId: id })],
        [1, () => gradeApi.updatePopularStatus({ editId: id })],
        [2, () => gradeApi.updateScoreStatus({ editId: id })],
      ]);
    };

    const handleUpdateStatusTask = async (number, data) => {
      const api = defineApiMap(data).get(number) as () => Promise<
        AxiosResponse<any, any>
      >;
      const result: any = await api();
      if (result.code != 200) {
        message.error(result.message);
      }
      message.success($t("base.stateUpdateSuccess"));
      fetchList();
    };
    tmp_proxy.$confirm({
      closable: true,
      maskClosable: true,
      icon: null,
      title: () => (
        <>
          {tableActiveKey.value === 0
            ? $t("base.memeber")
            : tableActiveKey.value === 1
            ? $t("base.popular")
            : $t("base.score")}
          {$t("base.updateLevelState")}
        </>
      ),
      style: {
        top: "30%",
      },
      content: (
        <>
          {data.status === 0
            ? `${$t("grade40")}"${data.name}"
           ${$t("grade39")}`
            : `${$t("grade40")}"${data.name}"
            ${$t("grade38")}`}
        </>
      ),
      onOk: async () => {
        try {
          handleUpdateStatusTask(tableActiveKey.value, data);
        } catch (error: any) {
          message.error(error.message);
        } finally {
        }
      },
      onCancel: () => {},
    });
  };
  const handleDetail = async (number) => {
    if (number === 2) {
      await fetchScoreDataById(data);
      drawerTitle.value = $t("base.detail");
    }
    showDrawer();
  };
  return new Map([
    [/^add_[0-2]$/, handleAdd],
    [/^update_[0-2]$/, handleUpdate],
    [/^update->status_[0-2]$/, handleUpdateStatus],
    [/^view_[0-2]$/, handleDetail],
  ]);
};
export const set_formState = async (
  type: string,
  formState: any = {},
  data: any = {}
) => {
  if (!type) {
    initObjAttr(formState, data, "origin", false);
    return;
  }
  resetFormState(formState);
  const handleApiTask = (string, number) => {
    let apiMap = [...defineGetDataApiMap(data)].filter(([key]) =>
      key.test(`${string}_${number}`)
    );
    apiMap.forEach(([, api]) => api.call(this, number));
  };
  handleApiTask(trimAll(type), tableActiveKey.value);
};
export const drawer_disable_ok_button = computed(() => {
  if (tableActiveKey.value === 0) {
    return (
      isEmptyType(drawerFormState.url) ||
      isEmptyType(drawerFormState.src) ||
      isEmptyType(drawerFormState.icon) ||
      isEmptyType(drawerFormState.indate) ||
      isEmptyType(drawerFormState.price) ||
      isEmptyType(drawerFormState.status) ||
      isEmptyType(drawerFormState.color)
    );
  }
  if (tableActiveKey.value === 1) {
    return (
      isEmptyType(drawerFormState.url) ||
      isEmptyType(drawerFormState.icon) ||
      isEmptyType(drawerFormState.name) ||
      isEmptyType(drawerFormState.title) ||
      isEmptyType(drawerFormState.rule) ||
      isEmptyType(drawerFormState.status) ||
      isEmptyType(drawerFormState.color)
    );
  }
  if (tableActiveKey.value === 2) {
    return (
      isEmptyType(drawerFormState.icon) ||
      isEmptyType(drawerFormState.name) ||
      isEmptyType(drawerFormState.rule) ||
      isEmptyType(drawerFormState.status)
    );
  }
  return true;
});
export const defaultSearchList = reactive([[], [], []]);
export let searchList = ref(defaultSearchList[tableActiveKey.value]);
export const queryParams = reactive<any>({});
export const vipLevelColorOptions = ref<any>([]);
export const popularBackgroundColorOptions = ref<any>([]);
export const vipValidMap = ref<any>([]);
watch(
  [() => tabPower[0], () => tabPower[1], () => tabPower[2]],
  (newArrayState) => {
    if (newArrayState.some((item) => item === true))
      initObjAttr(columns, defaultColumns[tableActiveKey.value]);
    if (newArrayState.every((item) => item === false)) initObjAttr(columns, []);
  }
);
